package com.vict.config;

import cn.hutool.setting.Setting;
import com.alibaba.fastjson.JSONArray;
import com.vict.bean.DbConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Slf4j
@Component
public class SettingConfig {

    public static File configFile;
    public static Setting setting;

    public static final String key_dbConfig = "dbConfig";

    public void init(){
        log.info("初始化配置文件");
        SettingConfig.configFile = loadConfigTxt();

        SettingConfig.setting = new Setting(configFile.getAbsolutePath());

        // 初始化banKuaiMoneyCron
        // String dbConfig = setting.getStr(key_dbConfig);
        // if(dbConfig == null || dbConfig.trim().equals("")){
        //     setting.set(key_banKuaiMoneyCron, banKuaiMoneyCron);
        //     setting.store();
        // }

        log.info("初始化配置完毕");
    }

    public static String getDbConfig(){
        return setting.getStr(key_dbConfig);
    }

    /**
     * 获取数据库配置
     */
    public static List<DbConfig> getDbConfigList(){
        String dbConfig = getDbConfig();
        if(dbConfig == null || dbConfig.trim().equals("")){
            return null;
        }
        List<DbConfig> dbConfigs = JSONArray.parseArray(dbConfig, DbConfig.class);
        return dbConfigs;
    }

    public static void saveDbConfig(List<DbConfig> dbConfigs){
        setting.set(key_dbConfig, JSONArray.toJSONString(dbConfigs));
        setting.store();
    }

    /** 加载本地配置文件 */
    public File loadConfigTxt() {
        try{
            if(Init.isInit){ // 已经初始化过
                File file = new File("config.setting");
                return file;
            }else{
                File file = new File("config.setting");
                if(file.exists()){
                    file.delete();
                }
                file.createNewFile();
                return file;
            }
        }catch(Exception e){
            log.error("", e);
        }
        throw new RuntimeException("加载本地配置文件异常");
    }
}
